<?php
    class Admin_TourController extends Main_Controller_Action
    {
        private $_arrParam;
        private $_tour;
        private $_similar;
        
        public function init(){
            $this->loadTemplates('admin');
            $this->_arrParam = $this->_request->getParams();
            $this->_tour = new Admin_Model_Tour();
            $this->_similar= new Admin_Model_Similar();
        }
        
        
        public function preDispatch(){
        	$auth = Zend_Auth::getInstance();
        	if(!$auth->hasIdentity()){
        		if($this->_request->getActionName() != 'login'){
        			$this->_redirect('admin/index/login');
        		}
        	}
        }
        
        
         public function taolayenAction()
    {
        echo "Tao la Yen day";
    }
    
    
        public function indexAction(){
            $this->view->headTitle('Quản lý tour');
            
            if($_POST['add']){
                $this->_redirect('admin/tour/create');
            }
            if($_POST['refresh']){
				$this->_redirect('admin/tour');
			}
            if($_POST['delete']){
                $listId = $this->_arrParam['check'];
				$this->_tour->deleteTours($listId);
				$this->_redirect($_SERVER['HTTP_REFERER']);
            }
            
            
            
            $list = $this->_tour->listTour();
            $adapter = new Zend_Paginator_Adapter_DbSelect($list);
            $paginator = new Zend_Paginator($adapter);
            $paginator->setItemCountPerPage(20);
            $paginator->setPageRange(5);
            $currentPage = $this->_request->getParam('page', 1);
            $paginator->setCurrentPageNumber($currentPage);
            $this->view->data = $paginator;
            $this->view->total = $paginator->getTotalItemCount();
            
            
            
           
        }
        
        public function helloAction()
        {
            $this->view->a='a';
        }
        
        public function createAction(){
            
            // Lay danh sach place
            
            $model= new Admin_Model_Place();
            $places= $model->listPlace();
            $this->view->places=$places;
        
            // Lay danh sach cac category
            
            $cat= new Admin_Model_Category();
            $cats=$cat->listCat();
            $this->view->cats=$cats;
    



            
            
            $this->view->headTitle('Thêm tour mới');
            $filter = new Zend_Filter_StringTrim();
            $tour_name = $filter->filter($this->_arrParam['tour_name']);
            $upload = new Zend_File_Transfer_Adapter_Http();
            
            $upload->addValidator('Size', false, 410000)
                   ->addValidator('Extension', false, 'jpg,jpeg,png,bmp,gif');
                   
            $info = $upload->getFileInfo();
            $tour_image = $upload->getFileName('tour_image', false);
            $start_place= $filter->filter($this->_arrParam['start_place']);
            $finish_place=$filter->filter($this->_arrParam['finish_place']);
            $description=$filter->filter($this->_arrParam['description']);
            
            $start_date=$filter->filter($this->_arrParam['start_date']);
          
            $start_date=$this->_tour->convertToMysql($start_date);
            
            $finish_date=$filter->filter($this->_arrParam['finish_date']);
           
            $finish_date=$this->_tour->convertToMysql($finish_date);
            
            
            $adult_price=$filter->filter($this->_arrParam['adult_price']);
            $children_price=$filter->filter($this->_arrParam['children_price']);
            $cat_id=$filter->filter($this->_arrParam['cat_id']);
            $create_date=date('Y-m-d');
            $status=$filter->filter($this->_arrParam['status']);
            
            $validate = new Admin_Form_ValidateTour();
            if($this->_request->isPost()){
                preg_match('#\.([^\.]+)$#', $tour_image, $matches);
				$fileExtension  = $matches[1];
                
				$newFileName = 'pic_' . time() . mt_rand(5, 99999999) . '.' . $fileExtension;
				$options = array('target' => BASE_PATH . '/public/img/tour/' . $newFileName,'overwrite'=>true);
				$upload->addFilter('Rename',$options,'tour_image');
				$upload->receive('tour_image');
                    
                        $flex = new Zendvn_Filter_RemoveCircumflex();
                        $lower  = new Zend_Filter_StringToLower();
                        $this->view->tourNameValue = $tour_name;
                        $data = array(
                            'tour_name' => $tour_name,
                            'tour_image' => $newFileName,
                            'start_place'=>$start_place,
                            'finish_place'=>$finish_place,
                            'description'=>$description,
                            'start_date'=>$start_date,
                            'finish_date'=>$finish_date,
                            'adult_price'=>$adult_price,
                            'children_price'=>$children_price,
                            'cat_id'=>$cat_id,
                            'create_date'=>$create_date,
                            'status'=>$status
                        );
                        $result = $this->_tour->addTour($data);
                        
                        $data['tour_id'] = $result;
                        $id=$result;
                        $data['tour_name_filter'] = $lower->filter($flex->filter($tour_name));
                        $this->_tour->saveAddItem($data, array('task' => 'add'));
                        
                        //$similar=array();
                        $simi=$this->_tour->Eve_Similar($id);
                       // var_dump($simi);die();
                        
                        // Chen du lieu vao bang Similar
                        $data1=array();
                        foreach($simi as $key => $value)
                        {
                            $data1=array(
                                'tour_1'=>$id,
                                'tour_2'=>$key,
                                'point'=>$value
                            
                            );
                            
                            
                            $this->_similar->insertSimilar($data1);
                            
                        }
                        
                        $this->_redirect('admin/tour');
                        
                    
                    /*
                    foreach($simi as $key =>$value)
                    {
                     
                      
                      
                  
                    $similar= new Admin_Model_Similar();
                    $similar->insertSimilar($data);
                   
                }*/
                    }
                
                }
                
            
        
        
        public function editAction(){
            
             // Lay danh sach place
            
            $model= new Admin_Model_Place();
            $places= $model->listPlace();
            $this->view->places=$places;
        
            // Lay danh sach cac category
            
            $cat= new Admin_Model_Category();
            $cats=$cat->listCat();
            $this->view->cats=$cats;
            
            
            $this->view->headTitle('Sửa tour');
            
            $tour_id = $this->_arrParam['tour_id'];
            $this->view->data = $this->_tour->getTourById($tour_id);
            
            $filter = new Zend_Filter_StringTrim();
            
            if($this->_request->isPost()){
                $filter = new Zend_Filter_StringTrim();
                // Lay du lieu tu form
                $tour_name = $filter->filter($this->_arrParam['tour_name']);
                $upload = new Zend_File_Transfer_Adapter_Http();
                $info = $upload->getFileInfo();
                
                $tour_image = $upload->getFileName('tour_image', false);
                $star_place= $filter->filter($this->_arrParam['start_place']);
                $finish_place=$filter->filter($this->_arrParam['finish_place']);
                $description=$filter->filter($this->_arrParam['description']);
                $start_date=$filter->filter($this->_arrParam['start_date']);
                $start_date=$this->_tour->convertToMysql($start_date);
                
                $finish_date=$filter->filter($this->_arrParam['finish_date']);
                $finish_date=$this->_tour->convertToMysql($finish_date);
                
                $adult_price=$filter->filter($this->_arrParam['adult_price']);
                $children_price=$filter->filter($this->_arrParam['children_price']);
                $cat_id=$filter->filter($this->_arrParam['cat_id']);
                $status=$filter->filter($this->_arrParam['status']);
                $validation = new Admin_Form_ValidateTour();
                $flag = 0;
                
                if($validation->validateTourName($tour_name)){
                    $this->view->tourNameValue = $tour_name;
                }
                else{
                    $this->view->error = 'Tên tour không được để trống và độ dài từ 1-50 kí tự';
                    $flag++;
                }
                if($this->view->data['tour_name'] != $tour_name){
                    if($this->_tour->checkTour($tour_name, $tour_id) > 0){
                        $this->view->error = 'Tên tour đã tồn tại';
                        $flag++;
                    }
                }
                
                if($flag == 0){
                    $flex = new Zendvn_Filter_RemoveCircumflex();
                    $lower = new Zend_Filter_StringToLower();
                    if(!$validation->validateImage($tour_image)) {
                        $data = array(
                           // 'tour_name' => $tour_name,
                            'tour_name' => $tour_name,
                            'start_place'=>$star_place,
                            'finish_place'=>$finish_place,
                            'description'=>$description,
                            'start_date'=>$start_date,
                            'finish_date'=>$finish_date,
                            'adult_price'=>$adult_price,
                            'children_price'=>$children_price,
                            'cat_id'=>$cat_id,
                            'status'=>$status
                        );
                    }
                    else {
                        preg_match('#\.([^\.]+)$#', $tour_image, $matches);
						$fileExtension  = $matches[1];
						$newFileName = 'pic_' . time() . mt_rand(5, 99999999) . '.' . $fileExtension;
						
						$options = array('target' => BASE_PATH . '/public/img/tour/' . $newFileName,'overwrite'=>true);
						$upload->addFilter('Rename',$options,'tour_image');
						$upload->receive('tour_image');
                        
                        if (is_file(PUBLIC_PATH . '/img/tour/' . $this->view->data['tour_image']))
						{
							unlink(PUBLIC_PATH . '/img/tour/' . $this->view->data['tour_image']);
						}
                        
                        $data = array(
                           // 'tour_name' => $tour_name,
                            'tour_name' => $tour_name,
                            'tour_image' => $newFileName,
                            'start_place'=>$star_place,
                            'finish_place'=>$finish_place,
                            'description'=>$description,
                            'start_date'=>$start_date,
                            'finish_date'=>$finish_date,
                            'adult_price'=>$adult_price,
                            'children_price'=>$children_price,
                            'cat_id'=>$cat_id,
                            'status'=>$status
                        );
                    }
                    
                    $this->_tour->editTour($data, $tour_id);
                    $data['tour_id'] = $tour_id;
                    $data['tour_name_filter'] = $lower->filter($flex->filter($tour_name));
                    $this->_tour->saveAddItem($data, array('task' => 'edit'));
                    
                    $this->_similar->deleteSimilar($tour_id);
                    $simi=$this->_tour->Eve_Similar($tour_id);
                    // Chen du lieu vao bang Similar
                    $data=array();
                    foreach($simi as $key => $value) {
                        $data=array(
                            'tour_1'=>$tour_id,
                            'tour_2'=>$key,
                            'point'=>$value
                        );
                        $this->_similar->insertSimilar($data);
                    }
                    $this->_redirect('admin/tour');
                }
            }
        }
        
        public function deleteAction(){
            $this->_tour->deleteTour($this->_arrParam['tour_id']);
            $this->_similar->deleteSimilar($this->_arrParam['tour_id']);
            $this->_redirect('admin/tour');
        }
        
        public function searchAction()
		{
			$this->view->headTitle('Tìm kiếm tour');
            $filter = new Zend_Filter_StringTrim();
            $flex   = new Zendvn_Filter_RemoveCircumflex();
            $lower  = new Zend_Filter_StringToLower();
            $flag   = 0;
            
			$keyword = $filter->filter($this->_arrParam['keyword']);
			$this->view->searchValue = $keyword;
				
			if($_POST['add']){
                $this->_redirect('admin/tour/create');
            }
            if($_POST['refresh']){
				$this->_redirect('admin/tour');
			}
            if($_POST['delete']){
                $listId = $this->_arrParam['check'];
				$this->_tour->deleteTours($listId);
				$this->_redirect($_SERVER['HTTP_REFERER']);
            }
			
			$validation = new Admin_Form_ValidateTour();
			if($validation->validateSearch($keyword))
			{
				$this->view->searchValue = $keyword;
			}
			else
			{
				$this->view->errorSearch = 'Bạn chưa nhập từ khóa';
                $keyword = $lower->filter($flex->filter($keyword));
                $keyword = 'tour_name_filter:' . $keyword;
				$result = $this->_tour->searchTour($keyword);
				$paginator = Zend_Paginator::factory($result);
				$paginator->setItemCountPerPage(40);
				$paginator->setPageRange(5);
				$currentPage = $this->_request->getParam('page', 1);
				$paginator->setCurrentPageNumber($currentPage);
					
				$this->view->total = count($result);
				$this->view->data = $paginator;
				$flag++;
			}
			
			if($flag == 0)
			{
                $keyword = $lower->filter($flex->filter($keyword));
                $keyword = 'tour_name_filter:' . $keyword;
				$result = $this->_tour->searchTour($keyword);
				$paginator = Zend_Paginator::factory($result);
				$paginator->setItemCountPerPage(40);
				$paginator->setPageRange(5);
				$currentPage = $this->_request->getParam('page', 1);
				$paginator->setCurrentPageNumber($currentPage);
				
				$this->view->total = count($result);
				$this->view->data = $paginator;
			}			
		}
        
        
        public function similarAction()
    {
        $tour= new Admin_Model_Tour();
        $simi=$tour->Eve_Similar(1);
        //var_dump($simi);die();
        $this->view->simi=$simi;
    }
    
    public function catAction()
    {
        $cat= new Admin_Model_Category();
        $name=$cat->getCatNameById(1);
        $this->view->name=$name;
    }
        
    }
